package com.school.PersonalAddressBook2;


import com.school.PersonalAddressBook.Contact;
import com.school.PersonalAddressBook.DatabaseConnection;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DataAccess {
    public void addContact(Contact contact) throws SQLException, IOException {
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement("INSERT INTO contacts(name, address, phone) VALUES (?, ?, ?)")) {
            stmt.setString(1, contact.getName());
            stmt.setString(2, contact.getAddress());
            stmt.setString(3, contact.getPhone());
            stmt.executeUpdate();
        }
    }

    public void updateContact(Contact contact) throws SQLException, IOException {
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement("UPDATE contacts SET name=?, address=?, phone=? WHERE id=?")) {
            stmt.setString(1, contact.getName());
            stmt.setString(2, contact.getAddress());
            stmt.setString(3, contact.getPhone());
            stmt.setInt(4, contact.getId());
            stmt.executeUpdate();
        }
    }

    public void deleteContact(int id) throws SQLException {
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement("DELETE FROM contacts WHERE id=?")) {
            stmt.setInt(1, id);
            stmt.executeUpdate();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Contact> listContacts() throws SQLException, IOException {
        List<Contact> contacts = new ArrayList<>();
        try (Connection conn = DatabaseConnection.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM contacts")) {
            while (rs.next()) {
                Contact contact = new Contact(rs.getInt("id"), rs.getString("name"), rs.getString("address"), rs.getString("phone"));
                contacts.add(contact);
            }
        }
        return contacts;
    }
}